package com.example.saiaadmin.filter;

import com.example.saiaadmin.common.JwtUtil;
import com.example.saiaadmin.common.RedisUtils;
import com.example.saiaadmin.entry.EbSystemUser;
import com.example.saiaadmin.mapper.EbSystemUserMapper;
import com.example.saiaadmin.po.CusterUserDetails;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * security请求前的认证过滤器
 */
@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private EbSystemUserMapper userMapper;
    @Autowired
    private RedisUtils redisUtils;
    private  List<String> excludeURLList =
            Stream.of("/eb-system-user/register", "/eb-system-user/login", "/eb-system-user/checkCode", "/eb-system-user/getCode").toList();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        String URI = request.getRequestURI();
        //boolean flag = excludeURLList.stream().anyMatch(element->element.equals(URI));
        //if (flag) {
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {

            filterChain.doFilter(request, response);
            return;
        }

        token = token.substring(7);

        int userid;
        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = (int) claims.get("id");
            username = (String) claims.get("username");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        String redisToken =  redisUtils.get(username+"Authorization");//已去掉Bearer
        if(!StringUtils.hasText(token)){
            throw new RuntimeException("token已过期");
        }
        if(!token.equals(redisToken)){
            throw new RuntimeException("token不合符");
        }

        EbSystemUser ebuser  = userMapper.selectById(userid);

        if (ebuser == null) {
            throw new RuntimeException("用户名未登录");
        }
        /*List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("admin"));
        list.add(new SimpleGrantedAuthority("role"));
        list.add(new SimpleGrantedAuthority("ROLE_admin"));
        User user = new User(username,ebuser.getPassword(), list);*/
        CusterUserDetails user=new CusterUserDetails(ebuser);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, null);

        // 如果是有效的jwt，那么设置该用户为认证后的用户
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        redisUtils.expire(username+"Authorization",7200L);
        filterChain.doFilter(request, response);
    }
}
